//
//  LoadData.m
//  News
//
//  Created by lanou3g on 15/11/5.
//  Copyright © 2015年 songhaowen. All rights reserved.
//

#import "LoadData.h"
#import "JQnewsModel.h"

static LoadData *loadData = nil;
@implementation LoadData

+(LoadData*)shareInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        loadData = [[LoadData alloc] init];
    });
    return loadData;
}

-(void)downLoadDataFinished:(Result)result WithUrl:(NSString *)url withCategory:(NSString*)category{
    
    
        
        //子线程网络请求
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            
            
            
            dispatch_async(dispatch_get_main_queue()
                           , ^{
                               [self.contentArray removeAllObjects];//清空放模型的数组
                           });
            
            
            
            //请求
            NSURLSession *session = [NSURLSession sharedSession];
            NSURLSessionTask *task = [session dataTaskWithURL:[NSURL URLWithString:url]completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                //解析
                NSDictionary *Dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                NSArray *allValueArray = Dict[category];
                for (NSDictionary *dict in allValueArray) {
                    JQnewsModel *contenModel = [[JQnewsModel alloc] init];
                    [contenModel setValuesForKeysWithDictionary:dict];
                    
                    [self.contentArray addObject:contenModel];
                    //NSLog(@"%@",self.contentArray);
                }
                
                
                
                //主线程刷新ui,调用block
                dispatch_async(dispatch_get_main_queue()
                               , ^{
                                   result();     //例:[self.tableView reloadData];
                               });
                
                
                
            }];
            [task resume];//开始
            
            
            
        });
        
 
}

//懒加载
- (NSMutableArray *)contentArray
{
    if (!_contentArray) {
        _contentArray = [NSMutableArray array];
    }
    return _contentArray;
}
@end
